<template>
  <dv-full-screen-container>
    <dv-loading>
      <div style="margin-bottom: 15px">
        <span>加载中..</span>
      </div>
      <el-button type="primary" icon="el-icon-refresh-left" @click="initPage">重试</el-button>
    </dv-loading>
  </dv-full-screen-container>
</template>

<script>
import { setToken, getToken, setRefreshToken, getRefreshToken } from "@/utils/auth";
import axios from "axios";
import api from "@/utils/api"; // 导入API工具
import { log } from "@/config"; // 导入安全的日志函数
import Cookies from "js-cookie";
import { postSSOInfoDirect } from "@/api/vadmin/login";
export default {
  name: "callback",
  methods: {
    async initPage() {
      try {
        if (process.env.NODE_ENV === 'development') {
          log.info("this.$route", this.$route);
        }
        let code = this.$route.query.code;
        let code_verifier = Cookies.get('pkce_code_verifier');
        // 使用API工具获取接口地址
        const tokenEndpoint = api.url('/sso/gettoken/');
        const response = await axios.post(tokenEndpoint, {
          code,
          code_verifier,
        });
        if (process.env.NODE_ENV === 'development') {
          log.info("response", response);
        }

        if (response.data && response.data.access_token) {
          // 存储access_token
          await setToken(response.data.access_token);

          // 更新store中的token
          await this.$store.commit("SET_TOKEN", response.data.access_token);

          try {
            // 获取用户信息
            const ssoResponse = await postSSOInfoDirect(response.data.access_token);
            const ssoInfo = ssoResponse.data; // 从axios响应中获取data
            console.log("SSO用户信息获取成功:", ssoInfo);
          } catch (error) {
            console.error("SSO用户信息获取失败:", error);
            // 不影响后续流程，只记录错误
          }


          // 存储refresh_token (如果有)
          if (response.data.refresh_token) {
            await setRefreshToken(response.data.refresh_token);
            await this.$store.commit("SET_REFRESH_TOKEN", response.data.refresh_token);
          }

          // 验证token是否存储成功
          const storedToken = getToken();


          if (storedToken) {
            try {

              // 清除可能的缓存数据，确保使用新token获取最新信息
              // 清除store中的用户信息缓存
              await this.$store.commit('SET_NAME', '');
              await this.$store.commit('SET_ROLES', []);
              await this.$store.commit('SET_PERMISSIONS', []);
              await this.$store.commit('SET_AVATAR', '');
              await this.$store.commit('SET_ID', '');

              // 清除路由缓存
              await this.$store.commit('SET_ROUTES', []);
              await this.$store.commit('SET_SIDEBAR_ROUTERS', []);
              // 获取用户信息
              await this.$store.dispatch("GetInfo");
              // 生成可访问路由表
              const accessRoutes = await this.$store.dispatch("GenerateRoutes");
              // 动态添加可访问路由表
              this.$router.addRoutes(accessRoutes);

              // 确保路由完整性
              await this.$nextTick();
              this.$router.replace("/");
            } catch (error) {
              log.error("获取用户信息失败:", error);
              this.$message.error("获取用户信息失败");
              // 清理相关token，避免循环
              await setToken('');
              await setRefreshToken('');
              this.$store.commit('SET_TOKEN', '');
              this.$store.commit('SET_REFRESH_TOKEN', '');
              this.$router.push("/401");
            }
          } else {
            this.$message.error("Token存储失败");
            this.$router.push("/401");
          }
        } else {
          this.$message.warning("获取token失败");
          this.$router.push("/401");
        }
      } catch (error) {
        log.error("验证失败:", error);
        this.$message.error("验证失败，请重试");
        // 清理相关token，避免循环
        await setToken('');
        await setRefreshToken('');
        this.$store.commit('SET_TOKEN', '');
        this.$store.commit('SET_REFRESH_TOKEN', '');
        this.$router.push("/401");
      }
    },
  },
  created() {
    this.initPage();
  },
};
</script>

<style lang="scss" scoped></style>
